import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService) {}

  /**
   * Generate JWT token
   * @private
   * @param payload {JwtPayload}
   * @param expiresIn {string}
   * @returns JWT
   */
  public generateToken(payload, expiresIn: string): string {
    const token = this.jwtService.sign(payload, { expiresIn });
    return token;
  }

  public async getTokenUser(tokens: string) {
    const parts = tokens.trim().split(' ');
    const [, token] = parts;
    const result = await this.verifyToken(token);
    return result;
  }

  /**
   * Verify JWT service
   * @param token JWT token
   * @param type {TokenType} "refresh" or "access"
   * @returns decrypted payload from JWT
   */
  private verifyToken(token: string) {
    return this.jwtService.verify(token);
  }
}
